<script setup>
import {ref, reactive, inject, watch, provide} from 'vue'
import LabelModify from './label_editor/LabelModify.vue'
import {useDialog,useMessage} from 'jiuqi-ui'
import {checkName, checkTitle} from "../../../utils/LabelCheck";
import LabelReference from "./LabelReference.vue";
import DeleteConfirmDialog from "../components/DeleteConfirmDialog.vue";
//================================================【组件通信】============================================================
//暴露 标签列表刷新 方法
defineExpose({
    refreshTableData
});


//发送请求组件
const context = inject('context')
//获取 当前标签分组
const { folderInfo } = inject('labelFolder')


//控制  标签编辑模态框 是否 展示与隐藏
const modifyLabelVisible = ref(false)
provide('modifyLabelVisible', modifyLabelVisible)

//当前  编辑标签数据
const curLabelItem = reactive({
    id:'',
    pId: folderInfo.id,
    name:'',
    title:'',
    dimCode:'',
    isFormula: false,
    dimItemCodes:'',
    type:folderInfo.type,
    order:0,

    // 前端属性  表达式数据   方便编辑模态框进行处理
    formulaData:''
})
provide('curLabelItem', curLabelItem)

//控制  标签引用展示模态框 是否 展示与隐藏
const labelReferenceVisible = ref(false)
provide('labelReferenceVisible',labelReferenceVisible)

//控制 删除确认对话框  显示与隐藏
const deleteConfirmDialogVisible = ref(false)
provide('deleteConfirmDialogVisible',deleteConfirmDialogVisible)
//================================================【公用相关】============================================================
//提示信息组件
const message = useMessage()
//对话组件
const dialog = useDialog()

//当前  是否为 复制操作
const isSaveas = ref(false)

//列表数据
const tableData = reactive([])
function refreshTableData() {
    return new Promise((resolve) => {
      if (folderInfo.id){
        context.getPlugin('http').get('/labelmanager/label/list?pId=' + folderInfo.id)
            .then(res => {
              tableData.length = 0
              for (let i = 0; i < res.data.length; i++) {
                res.data[i].process_order = i+1

                //临时修改   取值方式是表达式的改为维度项
                res.data[i].isFormula = false
                res.data[i].data_way = res.data[i].isFormula ? '表达式' : '指定数据项'

                tableData.push(res.data[i])
              }

              if (searchWord.value !== '') labelSearch(searchWord.value)
              resolve()
            })
      }
      else{
        tableData.splice(0,tableData.length)
        resolve()
      }

    })
}

//输入框搜索内容
const searchWord = ref('')
//================================================【组件属性】============================================================
//监听  当前选中标签分组id  是否变化
watch(()=>folderInfo.id, () => {
    labelSearch(searchWord.value)
}, { deep: true })
watch(()=>searchWord.value,(newValue)=>{
    labelSearch(newValue);
})
//================================================【普通方法】============================================================
//==================================================================【搜索框相关】
function labelSearch(searchKey) {
    if (searchKey !== '') {
        refreshTableData().then(()=>{
            const tempArr = tableData.filter(preFilterItem => {
                return preFilterItem.title.indexOf(searchKey) !== -1
                    ||
                    preFilterItem.name.indexOf(searchKey.trim().toLowerCase()) !== -1
                    ||
                    preFilterItem.name.indexOf(searchKey.trim().toUpperCase()) !== -1
            })
          tableData.splice(0, tableData.length)
          for (let i = 0; i < tempArr.length; i++) {
            let tempItem = tempArr[i];
            tempItem.process_order = i + 1;
            tableData.push(tempItem)
          }
        })
    } else {
        refreshTableData()
    }
}
//==================================================================【表格相关】
//标签列表  ref
const labelTable = ref(null)
//标签列表 表头信息
const columns = ref([
    { title: '序号', resizable: true, align: 'center', key: 'process_order',width: 60},
    { title: '标识', resizable: true, align: 'left', key: 'name',poptip: true },
    { title: '名称', resizable: true, align: 'left', key: 'title',poptip: true  },
    // { title: '取值方式', resizable: true, align: 'left', width: 200, key: 'data_way'},
    {title: '基础数据',resizable: true, align: 'left', key: 'dimTitle',poptip: true},
    { title: '操作', slot: 'controller', align: 'left', width: 300}
])
//编辑操作
function modify(rowData) {
    setCurLabelItem(curLabelItem,rowData)
    isSaveas.value = false
    modifyLabelVisible.value = true
}
//复制操作 设置成为 同步方法
async function saveas(rowData) {
    setCurLabelItem(curLabelItem,rowData)
    curLabelItem.id = ''

    //设置标签标识
    curLabelItem.name += '_FB1'
    await setSaveasLabelName()

    //设置标签标题
    curLabelItem.title += '_副本1'
    await setSaveasLabelTitle()

    isSaveas.value = true
    modifyLabelVisible.value = true
}
//获取最新标签名称
async function setSaveasLabelName(nameSuffix=1) {
    await checkName(context, curLabelItem).catch(() => {
        nameSuffix += 1
        //首先去除末尾数字 后拼接 最新数字
        curLabelItem.name = curLabelItem.name.replace(/\d+$/, "") + nameSuffix
        setSaveasLabelName(nameSuffix)
    });
}
//获取最新标签标题
async function setSaveasLabelTitle(titleSuffix=1) {
    await checkTitle(context,curLabelItem).catch(()=>{
        titleSuffix += 1
        //首先去除末尾数字 后拼接 最新数字
        curLabelItem.title = curLabelItem.title.replace(/\d+$/, "") + titleSuffix
        setSaveasLabelTitle(titleSuffix)
    });
}
function setCurLabelItem(labelItemObj,rowdataObj) {
    labelItemObj.id = rowdataObj.id
    labelItemObj.pId = rowdataObj.pId
    labelItemObj.name = rowdataObj.name
    labelItemObj.title = rowdataObj.title
    labelItemObj.dimCode = rowdataObj.dimCode
    labelItemObj.isFormula = rowdataObj.isFormula

    if (labelItemObj.isFormula) {
        labelItemObj.dimItemCodes = ''
        labelItemObj.formulaData = rowdataObj.dimItemCodes
    }else {
        labelItemObj.dimItemCodes = rowdataObj.dimItemCodes
        labelItemObj.formulaData = ''
    }

    labelItemObj.type = rowdataObj.type
    labelItemObj.order = rowdataObj.order
}
//删除操作
function remove(rowData) {
    setCurLabelItem(curLabelItem, rowData)

    context.getPlugin('http').get(`labelmanager/label/checkDelete/${curLabelItem.name}`)
        .then(({data}) => {

            if (data) {
                deleteConfirmDialogVisible.value = true
            } else {
                dialog.warning({
                    title: '提示',
                    content: '确认删除标签【' + curLabelItem.title + '】？',
                    onOk: () => {
                        context.getPlugin('http').get(`labelmanager/label/delete/${curLabelItem.id}`).then(() => {
                            refreshTableData().then(()=>{
                                message.success('标签删除成功')
                            })
                        }).catch(() => {
                            message.error('标签删除失败')
                        })
                    }
                })
            }

        })
}
//标签上移操作
function moveUp(index) {
    //目标标签
    let targetLabel = tableData[index - 1]
    //移动标签
    let moveLabel = tableData[index]
    changeLabelOrder(targetLabel,moveLabel)
}
//标签下移操作
function moveDown(index){
    //目标标签
    let targetLabel = tableData[index + 1]
    //移动标签
    let moveLabel = tableData[index]
    changeLabelOrder(targetLabel, moveLabel);
}
//交换紧邻的两个标签序号
function changeLabelOrder(targetLabel, moveLabel) {
    //交换序号
    const order = targetLabel.order
    targetLabel.order = moveLabel.order
    moveLabel.order = order

    const updateArr = [targetLabel, moveLabel]
    context.getPlugin('http').post('labelmanager/label/move', updateArr)
        .then(() => {
            refreshTableData()
        })
        .catch((errInfo)=>{
            message.error('移动失败',errInfo)
        })
}
//查看引用
function checkReference(rowData) {
    setCurLabelItem(curLabelItem,rowData)
    labelReferenceVisible.value = true
}
//================================================【生命周期】============================================================
</script>

<template>
    <div class="topSearch">
        <j-input
                v-model="searchWord"
                icon="icon-search"
                style="height:32px;width: 20%"
                placeholder="输入搜索内容"
                clearable
                @clear="searchWord === ''"
        ></j-input>
    </div>
  <j-table
          class="label-table-container"
          ref="labelTable"
          border
          :columns="columns"
          :data="tableData"
          height="calc(100% - 40px)">
      <template #controller="{row}">
          <j-space :size="15">
              <j-link  size="small" @click="modify(row)">编辑</j-link>
              <j-link  size="small" @click="saveas(row)">复制</j-link>
              <j-link  size="small" @click="remove(row)">删除</j-link>
              <j-link  size="small" @click="moveUp(row.process_order - 1)"
                      :disabled="row.process_order === 1">上移
              </j-link>
              <j-link  size="small" @click="moveDown(row.process_order - 1)"
                      :disabled="row.process_order === tableData.length">下移
              </j-link>
              <j-link  size="small" @click="checkReference(row)">查看引用</j-link>
          </j-space>
      </template>
  </j-table>
  <LabelModify
          v-if="modifyLabelVisible"
          :is-saveas="isSaveas"
  ></LabelModify>
  <LabelReference
          v-if="labelReferenceVisible"
  >
  </LabelReference>
  <!--标签 删除页面-->
    <DeleteConfirmDialog v-if="deleteConfirmDialogVisible" :is-folder="false"></DeleteConfirmDialog>
</template>


<!-- 全局样式 -->
<style scoped>
.topSearch{
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
    width: 100%;
    margin-bottom:8px;
}
.justify-span{
  width: 200px;
  display: inline-block;
  overflow: hidden;
  white-space: nowrap;
  text-align: justify;
  text-overflow: ellipsis;
  vertical-align: middle;
}
.label-table-container{
  height: 100%;
  min-width: 1300px;
  overflow: auto;
}
.label-table-container button:first-child{
  padding-left: 0px;
}
.label-table-container button{
  background-color: transparent !important;
}
</style>
